package mobi.greenplate.client.service;

import mobi.greenplate.client.service.response.CommunityListResponseHandler;
import java.util.List;
import mobi.greenplate.client.connect.ConnectionContext;
import mobi.greenplate.client.connect.DefaultResponseHandler;
import mobi.greenplate.client.converter.CommunityConverter;
import mobi.greenplate.client.domain.Community;
import mobi.greenplate.client.service.response.CommunityResponseHandler;

public class CommunityService extends AbstractBaseService {

    public CommunityService(ConnectionContext connectionContext) {
        super(connectionContext, "community");
    }

    public void delete(Long id, Long ownerId) {
        final int statusCodeDeleted = call().url(getUrlOwnedById(id,ownerId)).delete(new DefaultResponseHandler());
        assertDeleted(statusCodeDeleted, id);
    }

    public Community save(Community community, Long ownerId) {
         final String stringEntity = CommunityConverter.toXml(community);
        final DefaultResponseHandler defaultHandler = new DefaultResponseHandler();
        final Long id = community.getId();
        if (null == id) {
            //creating new
            final int statusCodeCreated = call().url(getServiceUrl()).stringEntity(stringEntity).post(defaultHandler);
            assertCreated(statusCodeCreated);
            //this is changing also the input parameter
            community.setId(defaultHandler.getId());
            return community;
        } else {
            //updating existing
            //for better performance is used the default handler and if the record is created is returned the same object
            //PUT acctually returns an xml which sould be processed with the concrete Handler
            final int statusCodeUpdated = call().url(getUrlById(id)).stringEntity(stringEntity).put(defaultHandler);
            assertExist(statusCodeUpdated, id);
            return community;
        }
    }

    public Community findById(Long id, Long ownerId) {
        final CommunityResponseHandler communityResponseHandler = new CommunityResponseHandler();
        final int statusCode = call().url(getUrlById(id)).get(communityResponseHandler);

        assertExist(statusCode, id);

        final Community result = communityResponseHandler.getCommunity();
        return result;
    }

    public List<Community> findByOwner(int firstResult, int maxResult, Long ownerId) {
         final CommunityListResponseHandler communityListResponseHandler = new CommunityListResponseHandler();
        final String pagedUrl = getPagedUrl(firstResult, maxResult);
        final int statusCode = call().url(pagedUrl).get(communityListResponseHandler);

        assertExist(statusCode, pagedUrl);
        final List<Community> result = communityListResponseHandler.getCommunityList();
        return result;
    }
}
